import { getUuid, isiOS } from './utils';
const reconnectTimeout = 4000
const SUBSCRIBE = '/ai_story/to_wechat/';
class Message {

    constructor(device_sn, newMessageHandle) {
        this.device_sn = device_sn;
        this.newMessageHandle = newMessageHandle;
        this.onConnect = this.onConnect.bind(this);
        this.onMessageArrived = this.onMessageArrived.bind(this);
        this.onConnectionLost = this.onConnectionLost.bind(this);
        this.connect_mqtt();
        this.isConnected = false;
    }

    // 连接丢失
    onConnectionLost(responseObject) {
        console.log(responseObject);
        if (responseObject.errorCode !== 0) {
            this.isConnected = false;
            // 处理自动连接
            this.autoReconnect();
        }
    }

    connect_mqtt() {
        const host = "mqtt.aidoor.net";
        let port = 8083;
        let useSSL = false;
        if (isiOS()) {
            port = 8084;
            useSSL = true;
        }
        const clientId = 'Web_' + getUuid() + '_' + new Date().getTime();
        console.log(`clientId:${clientId}`);
        // eslint-disable-next-line
        this.client = new Paho.MQTT.Client(host, port, clientId);
        this.client.onConnectionLost = this.onConnectionLost;
        this.client.onMessageArrived = this.onMessageArrived;

        var options = {
            timeout: 5,
            keepAliveInterval: 60,
            useSSL: useSSL,
            cleanSession: true,
            onSuccess: (function () {
                this.onConnect();
            }).bind(this),
            onFailure: (function (message) {
                this.autoReconnect();
            }).bind(this)
        }

        this.client.connect(options);
    }
    onConnect() {
        clearInterval(this.autoReconnectTimer)
        const topic = SUBSCRIBE + this.device_sn;
        console.log("MQTT 连接成功:开始订阅:" + topic);
        this.client.subscribe(topic, { qos: 0 });
        this.isConnected = true;
    }

    autoReconnect() {
        if (this.autoReconnectTimer) {
            clearInterval(this.autoReconnectTimer);
        }
        this.autoReconnectTimer = setInterval(() => {
            console.log("尝试重连..");
            this.connect_mqtt();
        }, reconnectTimeout);
    }

    onMessageArrived(message) {
        const topic = message.destinationName;
        try {
            const payload = message.payloadString;
            this.newMessageHandle(topic, payload);
        } catch (error) {
            console.log(' decode payload error ->', error);
        }
    }

}
export default Message;